package books.borrowing.bo.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import books.borrowing.EJBFacade;
import books.borrowing.bo.IBookBorrowingBo;
import books.borrowing.bo.IBookManagerClientService;
import books.borrowing.dao.impl.BookBorrowingDao;
import books.borrowing.entity.BookBorrowingEntity;
import books.storage.service.BookDto;

@Service("rentBo")
public class BookBorrowingBoImpl implements IBookBorrowingBo {

	@Autowired
	BookBorrowingDao rentDao;
	
	private static IBookManagerClientService _service;

	public void setBookBorrowingDao(BookBorrowingDao _rentDao) {
		this.rentDao = _rentDao;
	}

	public void save(BookBorrowingEntity _rent) throws Exception {
		this.rentDao.save(_rent);
	}

	public void update(BookBorrowingEntity _rent) {
		this.rentDao.update(_rent);
	}

	public void delete(BookBorrowingEntity _rent) {
		this.rentDao.delete(_rent);
	}

	public BookBorrowingEntity rentBook(String _login, String _ISBN)
			throws Exception {
		
		EJBFacade.getInstance();
		_service = EJBFacade.getBooksManager();
		BookDto _book = _service.findBook(_ISBN);
		if (_book == null)
			throw new Exception("Livre non trouvé !");
		_service.removeCopies(1, _book);
		
		return this.rentDao.rentBook(_login, _ISBN);
	}

	public BookBorrowingEntity returnBook(String _login, String _ISBN) {
		return this.rentDao.returnBook(_login, _ISBN);
	}

	@Transactional(readOnly = true)
	public List<BookBorrowingEntity> findRent(String _login, String _ISBN) {
		return this.rentDao.findRent(_login, _ISBN);
	}

	public List<BookBorrowingEntity> findSubscriberRents(String _login) {
		return this.rentDao.findSubscriberRents(_login);
	}
}
